<template>
  <div class="main">
    <div class="privilege_manage">
      <el-button type="primary" size="mini" @click="privilege_manage"
        v-if="rightsButtons['privilegeManage']"
        >特权管理</el-button
      >
    </div>
    <el-table
      :data="list"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      highlight-current-row
    >
      <el-table-column
        align="center"
        label="会员类型"
        prop="typeDesp"
      ></el-table-column>
      <el-table-column align="center" label="会员特权" prop="name">
        <template slot-scope="scope">
          <div class="privilege">
            <div
              class="privilege_item"
              v-for="(item, index) in scope.row.userPrivilegeItems"
              :key="index"
            >
              <img
                v-if="item.iconUrl"
                :src="item.iconUrl"
                class="avatar"
              />
              <div class="title">{{ item.title }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        v-if="rightsButtons['edit'] || rightsButtons['goods']"
      >
        <template slot-scope="scope">
          <el-button
            v-if="rightsButtons['edit']"
            type="primary"
            size="mini"
            @click="showEdit(scope.row)"
            >编辑</el-button
          >
          <router-link
            v-if="rightsButtons['goods']"
            :to="{
              name: 'upgradeMakeMoneyMemberGoods',
              params: { id: scope.row.id }
            }"
          >
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" v-if="listTotal > 0">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageIndex"
        :page-size="listQuery.pageSize"
        :total="listTotal"
        layout="total, prev, pager, next, jumper"
      ></el-pagination>
    </div>
    <el-dialog class="privilege_manage_dialog" title="特权管理"
       :visible.sync="privilege_manage_flag" width="80%" @close="privilege_manage_close">
      <div v-if="privilege_manage_removes.indexOf(index) == -1"
        :key="index"
        class="formList" v-for="(item,index) in formData.arr" @click="chiose(index)">
        <el-form class="privilege_manage_form" :model="item" :rules="privilege_manage_rules" size="medium" ref="form" label-width="100px">
          <el-form-item label="标题:" prop="title">
            <el-input v-model="item.title" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="图标:" prop="iconUrl">
            <el-upload
              class="avatar-uploader"
              accept="image/*"
              :action="upladUrl"
              name="file"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
            >
              <img v-if="item.iconUrl" :src="item.iconUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转链接:" prop="url" class="jump_link_group">
            <el-select v-model="item.selectUrl" placeholder="请选择" @change="dataChange">
              <el-option v-for="(item, index) in typeList" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-input
              v-if="links.includes(item.selectUrl)"
              v-model="item.url"
              placeholder="跳转地址"
            ></el-input>
            <!-- <function-type :item-data="jump_link_Protist[index]" :disable-types="[5, 50, 78]" @dataChange="dataChange" @getIndex="getIndex(index)" @custom_link="getCustomLink($event,index)" /> -->
          </el-form-item>
          <el-form-item label="排序:" prop="sort">
            <el-input type="number" v-model="item.sort" placeholder="越大越靠前"></el-input>
          </el-form-item>
          <el-form-item prop="operator">
            <div class="operator">
              <el-button type="infor" @click="del(index)">-移除</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="add()">+添加</el-button>
        <el-button type="primary" @click="save(0)" :loading="btnLoading"
          >保存</el-button
        >
        <el-button @click="privilege_manage_flag = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="editList.id ? '编辑' : '新建'" :visible.sync="showEditPop">
      <div class="edit">
        <!-- <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> -->
        <div class="vipType">类型：{{ editList.typeDesp }}</div>
        <el-checkbox-group
          v-model="checkList"
          class="checkList"
          @change="showEditCheckChange"
        >
          <div
            class="checkItem"
            v-for="(item, index) in checkListAll"
            :key="index"
          >
            <div class="img">
              <img
                v-if="item.iconUrl"
                :src="item.iconUrl"
                class="avatar"
                style="height: 30px;max-width: 80px;"
              />
            </div>
            <el-checkbox :label="item.title"></el-checkbox>
          </div>
        </el-checkbox-group>
        <div class="xckh">
            <el-input
              type="textarea"
              resize="none"
              v-model="slogan"
              placeholder="宣传口号"
              maxlength="20"
            ></el-input>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save(1)" :loading="btnLoading"
          >保存</el-button
        >
        <el-button @click="showEditPop = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import FunctionType from '../activity/h5/component/FunctionType.vue'
  export default {
    name: 'privilege',
    data() {
      return {
        typeLink: 0,
        links: ['0', '51', '14'],
        typeList: [
          { label: 'h5', value: "0" },
          // { label: '标签', value: 3 },
          // { label: '碧家精选', value: "4" },
          // { label: '碧选优品', value: "6" },
          // { label: '商品分类', value: "7" },
          { label: '箱起', value: "9" },
          { label: '拼团', value: "10" },
          { label: '碧划算', value: "12" },
          // { label: '淘宝官方活动', value: 13 },
          // { label: '团油', value: "14"},
          { value: "51", label: '碧选直播小程序' },
          { label: '今日热卖', value: "15"},
          // { value: "1", label: '商品' },
          // { value: "2", label: '套餐' },
          // { value: "201", label: '组合套餐' },
          // { value: "5", label: '活动' },
          // { value: "33", label: '箱起活动' },
          // { value: "34", label: '箱起礼包' },
          // { value: "50", label: '碧选小程序' },
          // { value: "77", label: '优惠券' },
          // { value: "78", label: '视频地址' },
          // { value: "88", label: '碧划算' },
          // { value: "35", label: '箱起商品' },
          // { value: "36", label: '箱起首页' },
          // { value: "37", label: '我的箱起' },

          { value: "38", label: '碧选首页' },
          { value: "39", label: '签到' },
          { value: "40", label: '我的好友' },
          { value: "41", label: '会员中心' },
          { value: "42", label: 'VIP支付页' },
          { value: "43", label: '钻石支付页' },
        ],
        list: [],
        index: 0, //选中的下标
        jump_link_Protist: [], //原生跳转数组
        editList: {}, //选中的编辑对象
        checkIds: [], //编辑时的选中的id
        checkList: [], //编辑时的选中项
        checkListAll: [], //固有选项
        slogan: '', //宣传口号
        privilege_manage_flag: false, //特权管理panel显示状态
        privilege_manage_removes: [],
        editIndex: 0, //当前编辑对象
        customLink: '',
        formData: {
          arr: [{
            deleteFlag: 1, //是否删除:0:删除,1:正常
            iconUrl: '', //图标
            selectUrlInt: -1, //下标
            selectUrl: '', //筛选原生跳转地址
            sort: '', //排序
            title: '', //标题
            url: ''
          }
        ]
      },
      formDataOld: {},
      privilege_manage_rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        iconUrl: [{ required: true, message: '请选择图标', trigger: 'change' }],
        sort: [{ required: true, message: '请输入序号', trigger: 'change' }]
      },
      listQuery: {
        pageIndex: 1,
        pageSize: 20,
        isPage: 1
      },
      listTotal: 0,
      listLoading: false,
      form: {},
      rules: {
        slogan: [
          { required: true, message: '不能为空'}
        ],
      },
      showEditPop: false,
      btnLoading: false
    }
  },
  components: {
    FunctionType
  },
  created() {
    this.getList()
    this.getPrivilegeConfigs()
  },
  methods: {
    parseNumber(str) {
      return Number(str)
    },
    privilege_manage_close() {
      this.privilege_manage_removes = []
      this.btnLoading = false
    },
    add() {
      this.formData.arr.push({
        deleteFlag: 1, //是否删除:0:删除,1:正常
        iconUrl: '', //图标
        selectUrl: '', //筛选原生跳转地址
        sort: '', //排序
        title: '', //标题
        url: ''
      })
      this.jump_link_Protist.push({
        subtitle: '',
        type: '',
        type_val: ''
      })
    },
    del(index) {
      // this.formData.arr.splice(index, 1)
      this.privilege_manage_removes.push(index)
      console.log(this.privilege_manage_removes)
      // this.formData.arr[index].deleteFlag = 0
      this.jump_link_Protist.splice(index, 1)
    },
    getCustomLink(data, index) {
      this.customLink = data
      this.formData.arr[index].url = data
      this.formData.arr[this.index].selectUrl = ''
    },
    getIndex(index) {
      this.index = index
    },
    dataChange(e) {
      console.log(e)
      // this.formData.arr[this.index].selectUrl = arguments[0].type_val
      // this.jump_link_Protist[this.index] = arguments[0]
    },
    showEditCheckChange(e) {
      let that = this
      that.checkIds = []
      for (let item in that.checkList) {
        for (let item_a in that.checkListAll) {
          if (that.checkListAll[item_a].title == that.checkList[item]) {
            that.checkIds.push(that.checkListAll[item_a].id)
          }
        }
      }
    },
    //选中编辑行
    chiose(index) {
      this.editIndex = index
    },
    uploadImg(e) {
      const file = e.target.files[0]
      console.log(file)
      this.picFileUpload(file, res => {
        console.log(res.filePath)
      })
    },
    privilege_manage() {
      this.privilege_manage_flag = true
      this.getPrivilegeConfigs()
    },

    //获取特权配置列表
    getPrivilegeConfigs(){
      this.request({
        url: '/bsnl-member/member/privilege/config',
        method: 'get'
      }).then(res => {
        console.log(res)
        if (res.status == 200) {
          this.checkListAll = res.data
          this.formData.arr = res.data
          this.formData.arr.forEach((item, index) => {
            this.jump_link_Protist.push({
              subtitle: '',
              type: '',
              type_val: ''
            })
          })
          if(this.$refs.form){
            this.$nextTick(() => {
              for (let i = 0; i < this.$refs.form.length; i++) {
                const element = this.$refs.form[i];
                element.clearValidate()
              }
            })
          }
        }
      })
    },
    // 获取列表
    getList() {
      this.request({
        url: '/bsnl-member/member/privilege',
        method: 'get'
      }).then(res => {
        if (res.status == 200) {
          this.list = res.data
          this.listLoading = false
        }
      })
    },
    showEdit(row) {
      this.editList = row
      this.slogan = row.slogan
      this.checkList = []
      for (let item in row.userPrivilegeItems) {
        this.checkList.push(row.userPrivilegeItems[item].title)
      }
      //开启dialog
      this.showEditPop = true
    },
    beforeUpload(file) {
      if (!/image/.test(file.type)) {
        this.$message.error('只能上传图片')
        return false
      }
      if (file.size > 1024 * 1024) {
        this.$message.error('图片不能大于1M')
        return false
      }
    },
    uploadSuccess(res) {
      this.formData.arr[this.editIndex].iconUrl = this.replaceImgUrl(
        res.filePath
      )
    },
    handleCurrentChange(val) {
      this.listQuery.pageIndex = val
      this.getList()
    },
    save(type) {
      const that = this
      console.log(type)
      this.btnLoading = true
      switch (type) {
        case 0: //特权管理
          let flag = true
          for (let i = 0; i < this.$refs.form.length; i++) {
            const element = this.$refs.form[i]
            element.validate(valid => {
              if (!valid) {
                flag = false
                return false
              }
            })
          }
          console.log(flag)
          if (flag) {
            console.log(that.privilege_manage_removes)
            that.privilege_manage_removes.forEach((item, index) => {
              that.formData.arr[item].deleteFlag = 0
            })
            this.request({
              url: '/bsnl-member/member/privilege/config',
              method: 'post',
              data: that.formData.arr
            }).then(res => {
              console.log(res)
              if (res.status == 200) {
                this.getList()
                this.btnLoading = false
                this.showEditPop = false
                this.privilege_manage_flag = false
                this.$message.success('保存成功')
              }
            })
          } else {
            this.btnLoading = false
          }
          break
        case 1: //会员列表
          if (this.slogan == '') {
            this.$message.error('备注不能为空!')
            this.btnLoading = false
            return
          }
          this.request({
            url: `/bsnl-member/member/privilege/${this.editList.id}`,
            method: 'post',
            params: {
              privilege: that.checkIds.join(','),
              slogan: that.slogan
            }
          })
            .then(res => {
              if (res.status == 200) {
                this.getList()
                this.btnLoading = false
                this.showEditPop = false
                this.$message.success('保存成功')
              }
            })
            .catch(err => {
              this.$message.error(err.message)
            })
          break
        default:
      }
    },
    couponDelete(index) {
      this.form.upgradeMakeMoneyCoupons.splice(index, 1)
    },
    chooseCoupon() {
      this.couponChoose(
        {
          validFlag: true
        },
        this.form.upgradeMakeMoneyCoupons
      ).then(val => {
        this.form.upgradeMakeMoneyCoupons = val
      })
    }
  }
}
</script>
<style lang="scss">
  .xckh {
    margin: 20px 0;
  }
  .el-checkbox {
    transform: translateY(20px);
  }
  .flex-container {
    display: flex;
  }
  .jump_link_group {
    flex: 3 !important;
  }
  .operator {
    display: flex;
  }
  .jump_link {
    display: flex;
  }

  @media screen and (min-width: 1435px) {
    .privilege_manage_form {
      display: flex;
      div {
        flex: 3;
      }
      div:nth-child(5) {
        flex: 1;
      }
    }
  }

.privilege_manage {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.checkList {
  display: flex;
  flex-wrap: wrap;
}

.checkItem {
  position: relative;
  margin: 20px 10px;
  width: 100px;
  display: flex;
  justify-content: center;
}

.checkItem .img {
  position: absolute;
  left: 20px;
  bottom: 0px;
}

// .el-checkbox__label {
//   padding-left: 40px !important;
// }

.privilege {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-around;
}

.privilege_item {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  flex-wrap: wrap;
  img {
    max-width: 80px;
    height: 30px;
  }
  .title {
    margin: 0 10px;
  }
}

.avatar-uploader {
  .el-upload {
    position: relative;
    width: 100px;
    height: 100px;
    line-height: 98px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
    box-sizing: border-box;
  }
}

.coupon_div {
  border: 1px solid #dcdfe6;
  min-height: 100px;

  .el-tag {
    margin-left: 10px;
  }
}
</style>
